import React from 'react';
import PropTypes from 'prop-types';
import { stripesConnect } from '@folio/stripes/core';
import { injectIntl,FormattedMessage } from 'react-intl';
import EditForm from './edit-form';

class FormSachet extends React.Component {
  // eslint-disable-next-line react/sort-comp
  constructor(props) {
    super(props);
    this.state = {
      ascriptionNameList: [],
      editParams: {},
      exitFlag: true,
      operator: {}
    };
  }

  static manifest = Object.freeze({
    httpClassifyInvoke: {
      type: 'okapi',
      accumulate: true,
      path: () => 'party/property'
    }
  });

  static propTypes = {
    mutator: PropTypes.shape({
      httpClassifyInvoke: PropTypes.shape({
        PUT: PropTypes.func.isRequired,
        POST: PropTypes.func.isRequired,
        GET: PropTypes.func.isRequired,
        DELETE: PropTypes.func.isRequired
      }),
      validate: PropTypes.shape({
        reset: PropTypes.func.isRequired,
        GET: PropTypes.func.isRequired
      }).isRequired
    }).isRequired,
    name:PropTypes.string,
    okapi:PropTypes.object,
    params:PropTypes.object,
    removeTopMenu:PropTypes.func,
    matchPath:PropTypes.string,
    toModel:PropTypes.func
  };

  // eslint-disable-next-line react/sort-comp
  editCommit = ({ requestPreferences, creds, ...formData }) => {
    if (formData.parentId == null) {
      formData.parentId = '0';
    }
    if (formData.parentId !== '0') {
      const parentId = formData.parentId;
      const group = this.state.ascriptionNameList;
      for (let i = 0; i < group.length; i++) {
        const item = group[i];
        if (item.id === parentId) {
          formData.parentName = item.label;
          break;
        }
      }
    }

    if (formData.sort == null) {
      formData.sort = 1;
    }
    formData.isDel = 0;
  
    formData.sort = parseInt(formData.sort);
    formData.operator = this.state.operator;
    delete formData.operator.addresses;
    delete formData.operator.preferredContactTypeId;
    delete formData.operator.servicePoints;
    delete formData.operator.curServicePoint;
    delete formData.operator.dateOfBirth;
    if (formData && formData.id) {
      this.update(formData);
    } else if (formData && !formData.id) {
      this.add(formData);
    }
  };

  add = data => {
    const {
      intl,
      mutator,
      history
    } = this.props;
    const { POST } = this.props.mutator.httpClassifyInvoke;
    POST(data).then(response => {
      // eslint-disable-next-line no-alert
      alert(intl.formatMessage({id:"ui-party.other.saved.successfully"}));
      this.cancel(false);
    });
  };

  update = data => {
    const {
      intl,
      mutator,
      history
    } = this.props;
    const { PUT } = this.props.mutator.httpClassifyInvoke;
    PUT(data).then(response => {
      alert(intl.formatMessage({id:"ui-party.other.saved.successfully"}));
      this.cancel(false);
    });
  };

  componentDidMount() {
    this.getAscriptionNameList();
    this.initData();
    // console.log(this.props);
    const { currentUser } = this.props.okapi;
    if (currentUser) {
      this.setState({
        operator: currentUser
      });
    }
  }

  getAscriptionNameList = () => {
    const val = JSON.stringify({ parentId: '0' });
    const {
      intl,
  
    } = this.props;
    const list = [
      {
        id: '',
        value: '0',
        label: intl.formatMessage({ id: 'ui-party.other.create.a.first-level.classification' })  
      }
    ];

    const { GET } = this.props.mutator.httpClassifyInvoke;
    GET({ params: { query: '( isDel = 0 and parentId == 0 )' } }).then(res => {
      const group = res.propertyGroup;
      for (let i = 0; i < group.length; i++) {
        const item = group[i];
        const tmp = {
          id: item.id,
          value: item.id,
          label: item.name
        };
        list.push(tmp);
      }
    });
    this.setState({
      ascriptionNameList: list
    });
  };

  cancel = (flag = true) => {
    const { removeTopMenu, matchPath } = this.props;
    removeTopMenu(matchPath, flag);
  };

  initData = () => {
    if (

      this.props.params &&
      this.props.params.id
    ) {
      const params = this.props.params;

      const { GET } = this.props.mutator.httpClassifyInvoke;
      GET({ path: `party/property/${params.id}` }).then(res => {
        this.setState({
          editParams: res
        });
      });
    }
  };

  render() {
    return (
      <EditForm
        onSubmit={this.editCommit}
        initialValues={this.state.editParams}
        cancel={this.cancel}
        httpValidatorInvoke={this.props.mutator.httpClassifyInvoke}
        ascriptionNameList={this.state.ascriptionNameList}
        exitFlag={this.state.exitFlag}
        toModel={this.props.toModel}
        removeTopMenu={this.props.removeTopMenu}
        form={this.props.name}
      />
    );
  }
}

export default injectIntl(stripesConnect(FormSachet));
